package com.easy.interceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求头中的 token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);

        // 验证 token是否存在且有效
        if (token==null || !TokenUtil.verify(token)) {
            Result result = new Result(401, "认证异常", null);
            //hutool
            String json = JSONUtil.toJsonStr(result);
            //fastjson
            json = JSON.toJSONString(result);

            // 返回结果
            response.getWriter().print(json);
            return false;
        }
        //放行
        return true;
    }
}
